package javacommon.authority.controller;

import javacommon.authority.model.User;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.core.Controller;
import com.jfinal.kit.EncryptionKit;

/**
 * 访问路径/
 * 
 * @author zhengwei
 * */
public class IndexController extends Controller {
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());
	public void index() {
		render("index.html");
	}

	public void login() {
		try {
			Subject subject = SecurityUtils.getSubject();
			String account = getPara("account");
			String pwd = getPara("password");
			UsernamePasswordToken token = new UsernamePasswordToken(account,
					EncryptionKit.md5Encrypt(pwd));
			token.setRememberMe(getPara("rememberme") != null);
			subject.login(token);
			setSessionAttr("user", User.dao.findFirstByAccount(account));

			redirect("/");// 跳转首页
		} catch (InvalidSessionException e) {
			e.printStackTrace();
			render("login.html");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			render("login.html");
		} catch (Exception e) {
			LOGGER.debug(e.getMessage());
			render("login.html");
		}
	}

	public void logout() {
		//getSession().invalidate();
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		render("login.html");
	}

	public void unauth() {
		render("unauth.html");
	}
}
